/**
 * author: Maxim Dybarskiy
 * date:   Jun 17, 2011
 * time:   5:08:27 PM
 */
import android.app.WallpaperManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Service extends android.app.Service {
    
    private long delay; // in seconds
    private String path;
    private int height;

    private Random random = new Random(System.currentTimeMillis());
    private ExecutorService executor = Executors.newCachedThreadPool();
    private WallpaperBinder binder = new WallpaperBinder();
    private WallpaperManager manager;
    
    @Override
    public IBinder onBind(Intent intent) {
       return binder;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        manager = WallpaperManager.getInstance(this);
        // start wallpapaer setting thread
        executor.execute(new SettingTask());
    }

    @Override
    public void onDestroy() {
        // stop wallpapaer setting thread
        executor.shutdownNow();
        // stop service
        super.onDestroy();
    }
    
    
    /**
     * Method for set wallpaper
     * @param image image for setting
     */
    private void setWallPaper(Bitmap image) {
        if (image != null) {
            try {
                Bitmap wp = Bitmap.createScaledBitmap(
                        image,
                        (int) (image.getWidth() / ((float) image.getHeight() / height)),
                        height,
                        true);
                manager.setBitmap(wp);
            } catch (IOException ex) {
                Log.e(Activity.LOG_PREFIX, "Can`t set wallpaper");
                Log.e(Activity.LOG_PREFIX, ex.getMessage());
            }
        }
    }
    
    class WallpaperBinder extends Binder {
        
        public void setPath(String path) {
            Service.this.path = path;
        }
        
        public void setDelay(int hours, int minutes) {
            Service.this.delay = hours * 1000 * 60 * 60 + minutes * 1000 * 60;
        }
        
        public void setHeight(int height) {
            Service.this.height = height;
        }
    }
    
    class SettingTask implements Runnable {
        
        private File[] getFileList() {
            File[] res = null;
            // get selected folder
            if (Service.this.path != null && !Service.this.path.equals("")) {
                File folder = new File(Service.this.path);
                if (folder.exists()
                        && folder.canRead()
                        && !folder.isFile()) {
                    // load content of folder (obly images: png, jpg, jpeg, bmp)
                    res = folder.listFiles(new FilenameFilter() {
                        @Override
                        public boolean accept(File dir, String name) {
                            String nameLowCase = name.toLowerCase();
                            return nameLowCase.endsWith("png")
                                    || nameLowCase.endsWith("jpg")
                                    || nameLowCase.endsWith("jpeg")
                                    || nameLowCase.endsWith("bmp");

                        }
                    });
                }
            }
            return res;
        }
        
        @Override
        public void run() {
            while (true) {
                try {
                    // wait for delay
                    Thread.sleep(Service.this.delay * 1000);
                    // get list of files
                    File[] files = getFileList();
                    if (files != null && files.length != 0) {
                        // get random index
                        int index = random.nextInt(files.length);
                        // load image
                        Bitmap bitmap = BitmapFactory.decodeFile(files[index].getAbsolutePath());
                        // set wallpaper
                        setWallPaper(bitmap);
                    }
                } catch (InterruptedException ex) {
                    Log.e(Activity.LOG_PREFIX, "Thread working error");
                    Log.e(Activity.LOG_PREFIX, ex.getMessage());
                }
            }
        }
    }
}
